package com.sinosoft.builder.mojo;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Iterator;
import java.util.List;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.project.MavenProject;

/**
 * CDK的Mojo抽象类
 * 
 * @author 潘巍（Peter Pan）
 * @since 2010-8-3 下午05:14:42
 */
public abstract class AbstractCDKMojo extends AbstractMojo {
	/**
	 * 顶层maven项目。
	 * 
	 * @parameter expression="${project}"
	 * @readonly
	 */
	protected MavenProject project;

	/**
	 * 元数据文件的位置
	 * 
	 * @parameter expression="src/main/resources/META-INF/metadata"
	 */
	protected File metadataFileDirectory;

	/**
	 * 配置文件
	 * 
	 * @parameter expression="src/main/resources/META-INF/service-config.xml"
	 */
	protected File configFile;

	/**
	 * 输出Java文件的目录。
	 * 
	 * @parameter expression="${project.build.directory}/generated/java"
	 */
	protected File outputJavaDirectory;

	/**
	 * 输出测试Java文件的目录
	 * 
	 * @parameter expression="${project.build.directory}/generated/test"
	 */
	protected File outputTestsDirectory;

	/**
	 * 输出资源文件的目录。
	 * 
	 * @parameter 
	 *            expression="${project.build.directory}/generated/resources"
	 */
	protected File outputResourcesDirectory;

	/**
	 * 创建项目的类加载器。
	 * 
	 * @param project
	 * @param useCCL
	 * @return
	 */
	protected ClassLoader createProjectClassLoader(MavenProject project,
			boolean useCCL) {
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		try {
			List<?> compileClasspathElements = project
					.getCompileClasspathElements();
			String outputDirectory = project.getBuild().getOutputDirectory();
			URL[] urls = new URL[compileClasspathElements.size() + 1];
			int i = 0;
			urls[i++] = new File(outputDirectory).toURI().toURL();
			for (Iterator<?> iter = compileClasspathElements.iterator(); iter
					.hasNext();) {
				String element = (String) iter.next();
				urls[i++] = new File(element).toURI().toURL();
			}

			if (useCCL) {
				classLoader = new URLClassLoader(urls, classLoader);
			} else {
				classLoader = new URLClassLoader(urls);
			}
		} catch (MalformedURLException e) {
			getLog().error("Classpath中包含错误的URL", e);
		} catch (DependencyResolutionRequiredException e) {
			getLog().error("依赖没有解决", e);
		}

		return classLoader;
	}

	/**
	 * 创建项目的类加载器。
	 * 
	 * @param project
	 * @return
	 */
	protected ClassLoader createProjectClassLoader(MavenProject project) {
		return createProjectClassLoader(project, true);
	}
}
